package cn.net.yugu.doraemon.api.common.model;

import java.io.Serializable;
import java.util.Objects;
import java.util.Optional;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class RpcResult<T> implements Serializable {

    private static final long serialVersionUID = 1247148143002050377L;

    public static final int OK = 200;

    private Integer code;
    private String message;

    private Long timestamp;

    private String localizedCode;

    private T data;

    public boolean isSuccess() {
        return Objects.equals(OK, code);
    }

    public static <T> RpcResult<T> buildSuccess() {
        return RpcResult.<T>builder()
                .code(OK)
                .message("OK")
                .timestamp(System.currentTimeMillis())
                .build();
    }

    public static <T> RpcResult<T> buildSuccess(T data) {
        return RpcResult.<T>builder()
                .code(OK)
                .message("OK")
                .data(data)
                .timestamp(System.currentTimeMillis())
                .build();
    }

    public static <T> RpcResult<T> buildSuccess(Optional<T> optional){
        if (optional == null || !optional.isPresent()) {
            return buildSuccess();
        }
        return buildSuccess(optional.get());
    }

    public static <T> RpcResult<T> buildFail(Exception e){
        return buildFail(500, e.getMessage());
    }

    public static <T> RpcResult<T> buildFail(Integer code,String message){
        return RpcResult.<T>builder()
                .code(code)
                .message(message)
                .timestamp(System.currentTimeMillis())
                .build();
    }

}
